﻿var draw = {
    cfg: {
        color: "#000",
        width: 1
    },
    board: null,
    parent: null,
    ctx: null,
    onie: false,
    init: function (id, config) {
        if (config) {
            this.cfg.color = config.color || this.cfg.color;
            this.cfg.width = config.width || this.cfg.width;
        }
        this.onie = ($.browser.msie);
        this.board = $(id);
        if (!this.board) {
            return;
        }

        //设置父控件属性
        this.parent = this.board.parent();
        this.parent.css("position", "relative").css("width", this.board.width()).css("height", this.board.height());

        var _id = "d" + new Date().getTime();
        if (!this.onie) {
            var canvas = "<canvas id='" + _id + "' style='top: 0; left: 0; position: absolute;z-index:99' width='" + this.board.width() + "' height='" + this.board.height() + "'></canvas>";
            this.parent.append(canvas);
            this.ctx = document.getElementById(_id).getContext("2d");
        }
        else {
            var div = "<div id='" + _id + "' style='position: absolute; left: 0; top: 0; z-index:99; width:" + this.board.width() + "px;height:" + this.board.height() + "px'></div>";
            this.parent.append(div);
        }
        this.board = $("#" + _id);

    },
    iedrawline: function (l) {
        var linestr = "<v:line strokecolor=" + l.color + " from='" + l.x1 + "," + l.y1 + "' to='" + l.x2 + "," + l.y2 + "'  classs='v' strokeweight='" + l.width + "'/>";
        this.board.append(linestr);
    },
    ffdrawline: function (l) {
        this.ctx.fillStyle = l.color;
        this.ctx.strokeStyle = l.color;
        this.ctx.lineWidth = l.width;
        this.ctx.beginPath();
        this.ctx.moveTo(l.x1, l.y1);
        this.ctx.lineTo(l.x2, l.y2);
        this.ctx.closePath();
        this.ctx.stroke();
        this.ctx.restore();
    },
    drawline: function (_x1, _y1, _x2, _y2, _color, _width) {
        var _l = {
            x1: _x1 || 0,
            y1: _y1 || 0,
            x2: _x2 || 0,
            y2: _y2 || 0,
            color: _color || this.cfg.color,
            width: _width || this.cfg.width
        }
        if (this.onie) {
            this.iedrawline(_l);
        }
        else {
            this.ffdrawline(_l)
        }
    }
}

function drawlines(objects, color) {
    for (i = 1; i < objects.length; i++) {
        var t1 = $(objects[i - 1]);
        var t2 = $(objects[i]);
        draw.drawline(t1.position().left + (t1.width() / 2 + 2),
            t1.position().top + (t1.height() / 2 + 2), 
            t2.position().left + (t2.width() / 2 + 2), 
            t2.position().top + (t2.height() / 2),
            color
        );   
    }
}